<template>
  <div class="actor-manage">
    <div class="page-header">
      <h2>演员管理</h2>
      <el-button type="primary" @click="handleCreate">
        <el-icon><Plus /></el-icon>
        新增演员
      </el-button>
    </div>
    
    <el-card>
      <template #header>
        <div class="table-header">
          <span>演员列表</span>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索演员姓名"
              style="width: 200px; margin-right: 10px;"
              clearable
            />
            <el-button @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="actorList" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="avatar" label="头像" width="100">
          <template #default="scope">
            <el-image
              v-if="scope.row.avatar"
              :src="scope.row.avatar"
              :preview-src-list="[scope.row.avatar]"
              fit="cover"
              style="width: 40px; height: 40px; border-radius: 4px;"
            />
            <span v-else style="color: #999;">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="nationality" label="国籍" width="100" />
        <el-table-column prop="birthday" label="生日" width="120">
          <template #default="scope">
            <span v-if="scope.row.birthday">{{ formatDate(scope.row.birthday) }}</span>
            <span v-else style="color: #999;">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="简介" min-width="200" show-overflow-tooltip />
        <el-table-column prop="movieCount" label="参演影片" width="100">
          <template #default="scope">
            <span>{{ scope.row.movieCount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'danger'">
              {{ scope.row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            <span v-if="scope.row.createdAt">{{ scope.row.createdAt }}</span>
            <span v-else style="color: #999;">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑演员对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :before-close="handleClose"
    >
      <el-form :model="actorForm" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="actorForm.name" placeholder="请输入演员姓名" />
        </el-form-item>
        
        <el-form-item label="头像" prop="avatar">
          <el-input v-model="actorForm.avatar" placeholder="请输入头像URL" />
          <div style="margin-top: 10px;">
            <el-image
              v-if="actorForm.avatar"
              :src="actorForm.avatar"
              style="width: 100px; height: 100px; border-radius: 4px;"
              fit="cover"
            />
          </div>
        </el-form-item>
        
        <el-form-item label="国籍" prop="nationality">
          <el-input v-model="actorForm.nationality" placeholder="请输入国籍" />
        </el-form-item>
        
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="actorForm.birthday"
            type="date"
            placeholder="选择生日"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            style="width: 100%;"
          />
        </el-form-item>
        
        <el-form-item label="简介" prop="description">
          <el-input
            v-model="actorForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入演员简介"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="actorForm.status"
            :active-value="true"
            :inactive-value="false"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { actorService } from '../../services/actorService'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')
const actorList = ref([])
const formRef = ref()

// 表单数据
const actorForm = reactive({
  id: null,
  name: '',
  avatar: '',
  nationality: '',
  birthday: '',
  description: '',
  status: true
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入演员姓名', trigger: 'blur' }
  ]
}

// 对话框标题
const dialogTitle = ref('新增演员')

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleDateString('zh-CN')
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  
  if (typeof dateTime === 'string') {
    return dateTime
  }
  
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 获取演员列表
const fetchActors = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value - 1,
      size: pageSize.value,
      search: searchKeyword.value
    }
    const response = await actorService.getActors(params)
    actorList.value = response.data.content || []
    total.value = response.data.totalElements || 0
  } catch (error) {
    console.error('获取演员列表失败:', error)
    ElMessage.error('获取演员列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchActors()
}

// 重置搜索
const handleReset = () => {
  searchKeyword.value = ''
  currentPage.value = 1
  fetchActors()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchActors()
}

// 当前页改变
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchActors()
}

// 新增演员
const handleCreate = () => {
  dialogTitle.value = '新增演员'
  Object.assign(actorForm, {
    id: null,
    name: '',
    avatar: '',
    nationality: '',
    birthday: '',
    description: '',
    status: true
  })
  dialogVisible.value = true
}

// 编辑演员
const handleEdit = (row) => {
  dialogTitle.value = '编辑演员'
  
  // 处理生日字段：如果已经是完整格式，提取日期部分
  let birthdayValue = row.birthday
  if (birthdayValue && birthdayValue.includes(' ')) {
    // 如果包含空格，说明是完整日期时间格式，提取日期部分
    birthdayValue = birthdayValue.split(' ')[0]
  }
  
  Object.assign(actorForm, {
    id: row.id,
    name: row.name,
    avatar: row.avatar,
    nationality: row.nationality,
    birthday: birthdayValue,
    description: row.description,
    status: row.status
  })
  dialogVisible.value = true
}

// 删除演员
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除演员"${row.name}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await actorService.deleteActor(row.id)
    ElMessage.success('删除成功')
    fetchActors()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除演员失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.clearValidate()
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 准备提交数据，将生日格式转换为后端期望的格式
    const submitData = {
      ...actorForm,
      // 如果生日存在，转换为后端期望的格式 "yyyy-MM-dd HH:mm:ss"
      birthday: actorForm.birthday ? `${actorForm.birthday} 00:00:00` : null
    }
    
    if (actorForm.id) {
      // 更新演员
      await actorService.updateActor(actorForm.id, submitData)
      ElMessage.success('更新成功')
    } else {
      // 新增演员
      await actorService.createActor(submitData)
      ElMessage.success('新增成功')
    }
    
    dialogVisible.value = false
    fetchActors()
  } catch (error) {
    if (error.errors) {
      ElMessage.error('请检查表单数据')
    } else {
      console.error('保存演员失败:', error)
      ElMessage.error('保存失败')
    }
  } finally {
    submitting.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchActors()
})
</script>

<style scoped>
.actor-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.el-image {
  cursor: pointer;
}
</style>